package server.server02;

import java.io.IOException;
import java.net.Socket;

/**
 * 分发器
 */
public class Dispatcher implements Runnable{
    private Socket client;
    private Request request;
    private Response response;
    public Dispatcher(Socket client) {
        this.client=client;
        //获取请求协议
        try {
            request =  new Request(client);
            //响应
            response = new Response(client);
        } catch (IOException e) {
            e.printStackTrace();
            release();
        }
    }

    @Override
    public void run() {
        try {
            Servlet servlet = WebApp.getServletFromeUrl(request.getUrl());
            if(null!=servlet){
                servlet.service(request,response);
                response.pushBrower(200);
            }else {
                //错误
                response.pushBrower(404);
            }
        }catch (Exception e){
            //错误
            try {
                response.pushBrower(500);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        release();//读取xml文件会阻塞，释放一下资源才能进来下次请求
    }
    //释放资源
    private void release(){
        try {
            client.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
